import React from "react";
import {Button, Checkbox, Form, Input, message} from "antd";
import "./Login.css";

import ParticlesBg from 'particles-bg'
import axios from "axios";
import {useNavigate} from "react-router-dom";

const Index = () => {

    const navigator = useNavigate();
    const onFinish = (values) => {
        console.log("Success:", values);
        let baseURL = "/users";
        axios.get(`${baseURL}?username=${values.username}&password=${values.password}&roleState=true&_expand=role`).then(res=>{
            // _expand 未生效
            axios.get(`/roles?id=${res.data[0].roleId}`).then(roles=>{
                Object.assign(res.data[0],{role:roles.data[0]})
                localStorage.setItem("token",JSON.stringify(res.data[0]))
            }).then(()=>{
                if (res.data.length === 0){
                    message.error("登入失敗")
                }else {
                    console.log(res.data)
                    navigator("/home")
                    message.success("欢迎回来")
                }
            })

        }).catch(()=>{
            message.error("登入失敗")
        })
    };
    return (
    <div style={{height: "100%" }}>
        <ParticlesBg type="random" bg={true} />
      <div className="formContainer">
        <div className="logintitle">全球新聞發佈系統</div>
        <Form
          layout="vertical"
          name="basic"
          style={{
            maxWidth: 600,
          }}
          initialValues={{
            remember: true,
          }}
          autoComplete="off"
          onFinish={onFinish}
        >
          <Form.Item
            label="Username"
            name="username"
            rules={[
              {
                required: true,
                message: "Please input your username!",
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="Password"
            name="password"
            rules={[
              {
                required: true,
                message: "Please input your password!",
              },
            ]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item
            name="remember"
            valuePropName="checked"
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Checkbox>Remember me</Checkbox>
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit">
              登錄
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Index;
